from heap.class_klass import Klass, HeapObject
from heap.jstring import JString


class BaseVM:
    def __init__(self):
        pass

    def initClass(self, thread, klass: Klass):
        klass.startInit()
        self.initSuperClass(thread, klass)
        self.scheduleClint(thread, klass)

    def createArgsArray(self, classLoader, arr, klass):
        argLen = len(arr)
        argsArr: HeapObject = klass.arrayClass().newArray(argLen)
        refs = argsArr.refs()
        for i in range(0, argLen):
            refs[i] = JString.internal(classLoader, arr[i])

        return argsArr

    def initSuperClass(self, thread, klass):
        if not klass.isInterface():
            superclass = klass.superClass
            if superclass is not None and not superclass.isInit():
                self.initClass(thread, superclass)

    def scheduleClint(self, thread, klass: Klass):
        clinit = klass.getClinitMethod()
        if clinit is not None:
            frame = thread.newFrame(clinit)
            thread.pushFrame(frame)